﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Common;
using Wuqi.Webdiyer;
using AjaxPro;
using Mang24k99.Model.GOLD;
using Mang24k99.Business.GOLD;
using Mang24k99.Business.COMM;
using Mang24k99.Business.CLMN;
using Mang24k99.Model.COMM;
using Mang24k99.Model.CLMN;
using System.Data.OleDb;
namespace Mang24k99.Web.GOLD.KtGoldImportprice
{
    public partial class ListEdit : System.Web.UI.Page
    {
        int tableid;
        int countryid;
        int unitid;
        int indexno;
        int labeldis;
        int typeindexno;
        string unitname;
        string tablename;
        string dataFreq;
        string modify = "";
        string pages;
        string strOrgFileName;
        string strFileExtension;
        string strCurFileName = "";
        string filename;
        protected string RootPath = VirtualPathUtility.ToAbsolute("~/");
        string _AspNetCostumHtmlName = "AspNetCostumHtmlName";
        public string AspNetCostumHtml
        {
            get
            {
                return ViewStateHelper.GetString(this.ViewState, _AspNetCostumHtmlName);
            }
            set
            {
                ViewStateHelper.SetViewState(this.ViewState, value,_AspNetCostumHtmlName);
            }
        }
        string _AddName = "Add";
        string _ModifyName = "Modify";
        string _NavTextName = "NavText";
        /// <summary>
        /// 分页的名称
        /// </summary>
        string _PageIndexName = "pageIndex";
        /// <summary>
        /// 操作的名称
        /// </summary>
        string _OpName = "op";
        /// <summary>
        /// 主键的名称
        /// </summary>
        string _IDName = "ID";
        /// <summary>
        /// Gets or sets the nav text.(保存lblNav.text的初始值)
        /// </summary>
        /// <value>The nav text.</value>
        public string NavText
        {
            get
            {
                return ViewStateHelper.GetString(ViewState,_NavTextName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _NavTextName);
            }
        }
        /// <summary>
        /// Gets or sets the index of the page.(保存修改时当前页)
        /// </summary>
        /// <value>The index of the page.</value>
        public  int? PageIndex
        {
            get
            {
                return ViewStateHelper.GetInt(ViewState, _PageIndexName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _PageIndexName);
            }
        }
        /// <summary>
        /// Gets or sets the primary ID.(主键id)
        /// </summary>
        /// <value>The primary ID.</value>
        public int? PrimaryID
        {
            get
            {
                return ViewStateHelper.GetInt(ViewState, _IDName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _IDName);
            }
        }
        /// <summary>
        /// Gets or sets the op.(操作符)
        /// </summary>
        /// <value>The op.</value>
        public string Op
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, _OpName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _OpName);
            }
        }
        
        /// <summary>
        /// Gets or sets the auth.(权限)
        /// </summary>
        /// <value>The auth.</value>
        public string Auth
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, "Auth");
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, "Auth");
            }
        }
       
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Auth))
            {
                Auth = CommonGrant.Auth.GetPageAuth(this);
                if (string.IsNullOrEmpty(Auth))
                {
                    return;
                }
            }
            else
            {
                CommonGrant.Auth.RefreshPageAuth(this);
            }
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Mang24k99.Business.GOLD.BKtGoldImportprice));
            if (!IsPostBack)
            {
                BindGridView();
                InitialParameter();
               
            }
        }
       
        /// <summary>
        /// Binds the ASP net pager.(绑定分页控件)
        /// </summary>
        private void BindAspNetPager()
        {
            AspNetPager aspNetPager = this.AspNetPager1;
            int RecordCount = BKtGoldImportprice.CountAll();
            aspNetPager.RecordCount = RecordCount;
            aspNetPager.CustomInfoHTML = string.Format(this.AspNetCostumHtml, aspNetPager.PageCount);
            if (!IsPostBack)
            {
                int pageIndex;
                try
                {
                    pageIndex = int.Parse(this.Request.QueryString["pageIndex"]);
                    this.AspNetPager1.CurrentPageIndex = pageIndex;
                    
                }
                catch (Exception)
                {
                }
            }
        }
        /// <summary>
        /// Binds the reapert.(绑定列表控件)
        /// </summary>
        private void BindReapert()
        {
            AspNetPager aspNetPager = this.AspNetPager1;
            Repeater repeater = this.Repeater1;
            int maxRecord = aspNetPager.PageSize;
            int startRecord = aspNetPager.StartRecordIndex - 1;
            object dataSource = BKtGoldImportprice.FindALLSlicedAll(startRecord, maxRecord);
            repeater.DataSource = dataSource;
            repeater.DataBind();
        }
        /// <summary>
        /// Handles the PageChanged event of the AspNetPager1 control.(列表改变时候)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindAspNetPager();
            BindReapert();
            CommonGrant.WebControlEnable.SetEnable(this, Auth);
        }
        /// <summary>
        /// Handles the PreRender event of the Repeater1 control.(列表程序之前)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Repeater1_PreRender(object sender, EventArgs e)
        {
            //Repeater repeater = (Repeater)sender;
            //IEnumerable repeaterObject=repeater.Items;
            //集体加客户端属性
            //PageOp.SetRepeaterAttributes(repeaterObject, "btnDelete", "onclick", "return ConfirmDelete()");
        }
        /// <summary>
        /// Handles the ItemCommand event of the Repeater1 control.(列表控件字段按钮事件)
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Button btnSource = e.CommandSource as Button;//事件按钮
            Button btnDelete = e.Item.FindControl("btnDelete") as Button;//删除按钮
            Button btnModify = e.Item.FindControl("btnModify") as Button;
            if (btnDelete.Enabled == false)
            {//防止客户端修改disable属性
                return;
            }
            if (btnModify.Enabled == false)
            {//防止客户端修改disable属性
                return;
            }
            object id;
            try
            {
                id = int.Parse(e.CommandArgument.ToString());
            }
            catch (Exception)
            {
                //转换失败忽略
                return;
            }
            if (btnSource.CommandName == btnDelete.CommandName)//若为删除按钮
            {
                Delete(id);
                Op = _AddName;
                MessageBox.Redirect(this, GetListUrl(this.AspNetPager1.CurrentPageIndex));
            }
            if (btnSource.CommandName == btnModify.CommandName)//为修改按钮
            {
                Op = _ModifyName;
                PrimaryID = TypeHelper.GetInt(id);
                PageIndex = this.AspNetPager1.CurrentPageIndex;
                BindData();
            }
        }
        protected void Delete(object id)
        {
            MKtGoldImportprice mKtGoldImportprice = BKtGoldImportprice.Find(id);
            if (mKtGoldImportprice != null)
            {
                BKtGoldImportprice.Delete(mKtGoldImportprice);
            }
        }
        protected void lnkbtnAdd_Click(object sender, EventArgs e)
        {
            GoUrl(_AddName);
        }
        private void GoUrl(string op)
        {
            string url = GetUrl(op);
            Response.Redirect(url, true);
        }
        private string GetUrl(string op)
        {
            int pageIndex = this.AspNetPager1.CurrentPageIndex;
            string url = "Edit.aspx" + "?" + "pageIndex=" + pageIndex + "&" + "op=" + op;
            return url;
        }
        protected void lnkbtnList_Click(object sender, EventArgs e)
        {
            GoServerListUrl(1);
            
        }
        /// <summary>
        /// Initials the parameter.(接受必要参数,无参数退出)
        /// </summary>
        private void InitialParameter()
        {
             this.btnSave.Attributes.Add("onclick", "return checkAll();");
            if (string.IsNullOrEmpty(Op))
            {
                Op = _AddName;
            }
            string strNavText = CommonGrant.Auth.GetPageNavText(this);
            NavText = strNavText + this.lblNav.Text;
            this.Title = strNavText + "   后台管理系统";
            
            //PageIndex = RequestHelper.GetInt(this, _PageIndexName);
            //PrimaryID = RequestHelper.GetInt(this, _IDName);
            //if (!PageIndex.HasValue)
            //{
            //    Response.End();
            //}
            BindData();
        }
        /// <summary>
        /// Binds the data.(绑定基础数据)
        /// </summary>
        private void BindData()
        {
            this.AspNetCostumHtml = this.AspNetPager1.CustomInfoHTML;
            BindDDL();
            Castle.Components.Validator.RunWhen runWhen = Castle.Components.Validator.RunWhen.Insert;
            if (StringHelper.Compare(Op, _AddName))
            {
                this.lblNav.Text = string.Format(NavText, "导入");
                this.btnSave.Text = "导 入";
                AspNetPager1_PageChanged(null, null);
            }
            else if (StringHelper.Compare(Op, _ModifyName))
            {
                if (!PrimaryID.HasValue)
                {
                    Response.End();
                }
                this.btnSave.Text = "修 改";
                SetNavTextToModify();
                //BindEdit();
            }
            else
            {
                Response.End();
                return;
            }
            Type typeMode = typeof(MKtGoldImportprice);
            WebHelper.SetWebControlAttributes(runWhen, typeMode, this.Controls[0].FindControl("form1").Controls[0].Controls);
        }
        /// <summary>
        /// Sets the nav text to modify.
        /// </summary>
        private void SetNavTextToModify()
        {
            this.lblNav.Text = string.Format(NavText, "修改");
        }
        /// <summary>
        /// Binds the DDL.(绑定ddl)
        /// </summary>
        private void BindDDL()
        {
            IList<MKtCommCodeList> modelsParentKtCommCodelistByBreedCode = BKtCommCodeList.FindAll2();
            //MKtCommCodeList valueParentKtCommCodelistByBreedCode = new MKtCommCodeList();
            //valueParentKtCommCodelistByBreedCode.CODE_NO = 0;
            //valueParentKtCommCodelistByBreedCode.CODE_CNAME = "--请选择--";
            //IList<MKtCommCodeList> sourceModelsParentKtCommCodelistByBreedCode = ListHelper<MKtCommCodeList>.GetList(modelsParentKtCommCodelistByBreedCode, valueParentKtCommCodelistByBreedCode);
            IList<MKtCommCodeList> sourceModelsParentKtCommCodelistByBreedCode = modelsParentKtCommCodelistByBreedCode;

            this.ddlParentKtCommCodelistByPriceType.DataSource = sourceModelsParentKtCommCodelistByBreedCode;
            this.ddlParentKtCommCodelistByPriceType.DataTextField = "CODE_CNAME";
            this.ddlParentKtCommCodelistByPriceType.DataValueField = "CODE_NO";
            this.ddlParentKtCommCodelistByPriceType.DataBind();
            
        }
        /// <summary>
        /// Binds the edit.(绑定编辑页面)
        /// </summary>
        //private void BindEdit()
        //{
        //    MKtGoldImportprice modelKtGoldImportprice = BKtGoldImportprice.Find(PrimaryID);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtProductName);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtProductUnit);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS1);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS2);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS3);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS4);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS5);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS6);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS7);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS8);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS9);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS10);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS11);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS12);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS13);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS14);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS15);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS16);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS17);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS18);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS19);
        //    WebHelper.SetControlValue(modelKtGoldImportprice, txtS20);
        //    if(modelKtGoldImportprice.MParentKtCommCodelistByPriceType != null)
        //    {
        //        ListItem ddlSelectedParentKtCommCodelistByPriceType = ddlParentKtCommCodelistByPriceType.Items.FindByValue(TypeHelper.GetString(modelKtGoldImportprice.MParentKtCommCodelistByPriceType.CODE_NO));
        //        if (ddlSelectedParentKtCommCodelistByPriceType != null)
        //        {
        //            ddlSelectedParentKtCommCodelistByPriceType.Selected = true;
        //        }
        //    }
        //    ddlParentKtCommCodelistByPriceType.Enabled = false;
        //}
    
        //protected void btnSave_Click(object sender, EventArgs e)
        //{
        //    if (this.btnSave.Enabled==false)
        //    {//防用户修改页面按钮disable属性
        //        return;
        //    }
        //    string msg = "";
        //    #region 接受操作参数
        //    bool isAdd = false;
        //    if (StringHelper.Compare(Op, _AddName))
        //    {
        //        isAdd = true;
        //    }
        //    else if (StringHelper.Compare(Op, _ModifyName))
        //    {
        //        isAdd = false;
        //    }
        //    else
        //    {
        //        return;
        //    }
        //    #endregion
        //    MKtCommCodeList mParentKtCommCodelistByPriceType = null;
        //    if (ddlParentKtCommCodelistByPriceType.SelectedValue == "")
        //    {
        //        msg = "PriceType必须选择" + "\r\n";
        //    }
        //    else
        //    {
        //        mParentKtCommCodelistByPriceType = BKtCommCodeList.Find(TypeHelper.GetInt(ddlParentKtCommCodelistByPriceType.SelectedValue));
        //       if (mParentKtCommCodelistByPriceType == null)
        //       {
        //           msg = "PriceType必须选择" + "\r\n";
        //       }
        //    }
        //    if (!String.IsNullOrEmpty(msg))
        //    {
        //        MessageBox.Show(this, msg);
        //        return;
        //    }
        //    #region 根据操作选项创建实例
        //    MKtGoldImportprice modelKtGoldImportprice;
        //    if (isAdd)
        //    {
        //        modelKtGoldImportprice = new MKtGoldImportprice();
        //    }
        //    else
        //    {
        //        modelKtGoldImportprice = BKtGoldImportprice.Find(PrimaryID);
        //        if (modelKtGoldImportprice == null)
        //        {
        //            return;
        //        }
        //    }
        //    #endregion
        //    modelKtGoldImportprice.MParentKtCommCodelistByPriceType = mParentKtCommCodelistByPriceType;
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtProductName);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtProductUnit);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS1);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS2);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS3);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS4);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS5);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS6);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS7);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS8);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS9);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS10);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS11);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS12);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS13);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS14);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS15);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS16);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS17);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS18);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS19);
        //    WebHelper.SetModelValue(modelKtGoldImportprice, txtS20);
        //    Castle.Components.Validator.RunWhen runWhen = Castle.Components.Validator.RunWhen.Update;
        //    if (isAdd)
        //    {
        //        runWhen = Castle.Components.Validator.RunWhen.Insert;
        //    }
        //    bool isSuccess = modelKtGoldImportprice.IsValid(runWhen);
        //    if (!isSuccess)
        //    {
        //        msg =ActiveRecordValidationBaseHelper.GetErrorMsg(modelKtGoldImportprice);
        //        MessageBox.Show(this,msg);
        //        return;
        //    }
        //    if (isAdd)
        //    {
        //        BKtGoldImportprice.Create(modelKtGoldImportprice);
        //        msg = "添加成功";
        //        MessageBox.ShowAndRedirect(this, msg, GetListUrl(0));
        //    }
        //    else
        //    {
        //        BKtGoldImportprice.Update(modelKtGoldImportprice);
        //        msg = "修改成功";
        //        MessageBox.ShowAndRedirect(this, msg, GetListUrl(PageIndex));
        //    }
        //}

        //protected void btnReturn_Click(object sender, EventArgs e)
        //{
           
        //    if (StringHelper.Compare(Op,_AddName))
        //    {
        //        MessageBox.Redirect(this, GetListUrl(this.AspNetPager1.CurrentPageIndex));
        //    }
        //    else
        //    {
        //        MessageBox.Redirect(this, GetListUrl(PageIndex));
        //    }
        //}
        private void GoServerListUrl(int? pageIndex)
        {
            string url = GetListUrl(pageIndex);
            Response.Redirect(url, true);
        }
        private string GetListUrl(int? pageIndex)
        {
            string op = "?" + "" + _PageIndexName + "=" + pageIndex;
            string url = "ListEdit.aspx" + op;
            return url;
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            Panel1.Visible = false;
            txtProductName.Text = "";
            InsertData();

        }

        private void InsertData()
        {
            //定义sheet1$表名
            string tableName = null;
            DataTable dt = new DataTable();
            string filename = uploadfile();

            if (filename == null || filename == "")
            {
                Page.RegisterClientScriptBlock("poi", "<script language=javascript>alert('请选择导入文件！');</script>");
                return;
            }

            string strConnUpload = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " + filename + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=1'";
            OleDbConnection connUpload = new OleDbConnection(strConnUpload);
            connUpload.Open();
            DataTable dtname = connUpload.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            //获取sheet1$表名
            tableName = dtname.Rows[0][2].ToString().Trim();
            //查询EXCEL
            string strSQL = "SELECT * FROM " + "[" + tableName + "]";
            OleDbDataAdapter daUpload = new OleDbDataAdapter(strSQL, connUpload);

            daUpload.Fill(dt);
            connUpload.Close();          
            //返回当前的数据格式          

            MKtGoldImportprice modelKtGoldImportprice = new MKtGoldImportprice();
            MKtCommCodeList mParentKtCommCodelistByPriceType = null;
            string msg = "";
            if (ddlParentKtCommCodelistByPriceType.SelectedValue == "")
            {
                msg = "PriceType必须选择" + "\r\n";
            }
            else
            {
                mParentKtCommCodelistByPriceType = BKtCommCodeList.Find(TypeHelper.GetInt(ddlParentKtCommCodelistByPriceType.SelectedValue));
                if (mParentKtCommCodelistByPriceType == null)
                {
                    msg = "PriceType必须选择" + "\r\n";
                }
            }
            if (!String.IsNullOrEmpty(msg))
            {
                MessageBox.Show(this, msg);
                return;
            }
            modelKtGoldImportprice.MParentKtCommCodelistByPriceType = mParentKtCommCodelistByPriceType;

            if (mParentKtCommCodelistByPriceType.CODE_NO == 31601 && dt.Columns.Count == 6)
            {               
                string[] titlenames = new string[6]{"商品名称","单位","美元价格","加元价格","欧元价格","英镑价格"
};
                string[] IDataTitle = new string[6];  
                for(int i=0;i<6;i++)
                {
                    IDataTitle[i] = dt.Columns[i].ColumnName;
                    if(IDataTitle[i] != titlenames[i])
                    {
                        MessageBox.Show(this, "请导入正确的表结构");
                        return;
                    }
                }
            }
            else if (mParentKtCommCodelistByPriceType.CODE_NO == 31602 && dt.Columns.Count == 2)
            {
                string[] titlenames = new string[2]{"商品名称","回收价格"};
                string[] IDataTitle = new string[2];
                for (int i = 0; i < 2; i++)
                {
                    IDataTitle[i] = dt.Columns[i].ColumnName;
                    if (IDataTitle[i] != titlenames[i])
                    {
                        MessageBox.Show(this, "请导入正确的表结构");
                        return;
                    }
                }
            }
            else if (mParentKtCommCodelistByPriceType.CODE_NO == 31603 && dt.Columns.Count == 4)
            {
                string[] titlenames = new string[4]{"黄金","远期利率","Libor","出借利率"};
                string[] IDataTitle = new string[4];
                for (int i = 0; i < 4; i++)
                {
                    IDataTitle[i] = dt.Columns[i].ColumnName;
                    if (IDataTitle[i] != titlenames[i])
                    {
                        MessageBox.Show(this, "请导入正确的表结构");
                        return;
                    }
                }
            }
            else
            {
                MessageBox.Show(this, "请导入正确的表结构");
                return;
            }
            
            List<string> IData = new List<string>();
            int rowcount = dt.Rows.Count;
            int columncount = dt.Columns.Count;

            if (HaveSameGroup(mParentKtCommCodelistByPriceType.CODE_NO.Value) && dt.Rows.Count > 0)
            {
                BKtGoldImportprice.Deletes(mParentKtCommCodelistByPriceType.CODE_NO.Value);
            }               


            for (int i = 0; i < rowcount; i++)
            {
                if (dt.Rows[i][0].ToString() == "")
               {
                   i++;
               }                

                int j;
                for (j = 0 ; j < columncount; j++)
                { 
                    IData.Add(dt.Rows[i][j].ToString().Trim());
                }
                for (int k = columncount; k < 22; k++)
                {
                    IData.Add("");

                }

                //if (HaveSameGroup(IData[0], IData[1]) && mParentKtCommCodelistByPriceType.CODE_NO == 31601)
                //{                    
                //    int PrimaryID = int.Parse(BKtGoldImportprice.FindFirstData(IData[0], IData[1]).ID.ToString());
                //    UpdateData(PrimaryID, IData);
                //}
                //else if (HaveSimpleSameGroup(IData[0]) && mParentKtCommCodelistByPriceType.CODE_NO == 31602)
                //{
                //    int PrimaryID = int.Parse(BKtGoldImportprice.FindFirstData2(IData[0],31602).ID.ToString());
                //    UpdateData(PrimaryID, IData);
                //}                 
                Add(IData);
               

                
                IData.Clear();
            }
            DeleteExecl(strCurFileName);
            BindGridView();
            MessageBox.Show(this, "导入成功");
        }

        private void BindGridView()
        {
             int selectvalue;
            if (ddlParentKtCommCodelistByPriceType.SelectedValue == "")
            {
                selectvalue = 31601;
            }
            else
            {
                selectvalue = int.Parse(ddlParentKtCommCodelistByPriceType.SelectedValue);
            }
            Panel1.Visible = false;
            IList<MKtGoldImportprice> obj = BKtGoldImportprice.FindAll(selectvalue);
            GridView2.DataSource = obj;
            GridView2.DataBind();

        }

        private void DeleteExecl(string strCurFileName)
        {
            string filename = "";
            filename = Server.MapPath("") + "\\upload\\" + strCurFileName;
            System.IO.File.Delete(filename);
        }

 private void UpdateData(int id, List<string> arrdata)
{
    Delete(id);    
}

//private bool HaveSameGroup(string name,string unit)
//{
//    if (BKtGoldImportprice.Count(name,unit) > 0)
//    {
//        return true;
//    }
//    else
//    {
//        return false;
//    }
//}


private bool HaveSameGroup(int codeno)
{
    if (BKtGoldImportprice.Count(codeno) > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//private bool HaveSimpleSameGroup(string name)
//{
//    if (BKtGoldImportprice.Count2(name) > 0)
//    {
//        return true;
//    }
//    else
//    {
//        return false;
//    }
//}

        private void Add(List<string> arrdata)
        {
            int datacount = arrdata.Count;
            MKtGoldImportprice modelKtGoldImportprice = new MKtGoldImportprice();
            MKtCommCodeList mParentKtCommCodelistByPriceType = null;
            string msg = "";
            if (ddlParentKtCommCodelistByPriceType.SelectedValue == "")
            {
                msg = "PriceType必须选择" + "\r\n";
            }
            else
            {
                mParentKtCommCodelistByPriceType = BKtCommCodeList.Find(TypeHelper.GetInt(ddlParentKtCommCodelistByPriceType.SelectedValue));
                if (mParentKtCommCodelistByPriceType == null)
                {
                    msg = "PriceType必须选择" + "\r\n";
                }
            }
            if (!String.IsNullOrEmpty(msg))
            {
                MessageBox.Show(this, msg);
                return;
            }
            modelKtGoldImportprice.MParentKtCommCodelistByPriceType = mParentKtCommCodelistByPriceType;

            if (mParentKtCommCodelistByPriceType.CODE_NO == 31601)
            {
                modelKtGoldImportprice.ProductUnit = arrdata[1];
                modelKtGoldImportprice.S1 = arrdata[2];
                modelKtGoldImportprice.S2 = arrdata[3];
                modelKtGoldImportprice.S3 = arrdata[4];
            }
            else if (mParentKtCommCodelistByPriceType.CODE_NO == 31602)
            {
                modelKtGoldImportprice.ProductUnit = "";
                modelKtGoldImportprice.S1 = arrdata[1];
                modelKtGoldImportprice.S2 = arrdata[3];
                modelKtGoldImportprice.S3 = arrdata[4];
                
            }
            else if (mParentKtCommCodelistByPriceType.CODE_NO == 31603)
            {
                modelKtGoldImportprice.ProductUnit = "";
                modelKtGoldImportprice.S1 = arrdata[1];
                modelKtGoldImportprice.S2 = arrdata[2];
                modelKtGoldImportprice.S3 = arrdata[3];
            }
            modelKtGoldImportprice.ProductName = arrdata[0];

           
            modelKtGoldImportprice.S4 = arrdata[5];
            modelKtGoldImportprice.S5 = arrdata[6];
            modelKtGoldImportprice.S6 = arrdata[7];
            modelKtGoldImportprice.S7 = arrdata[8];
            modelKtGoldImportprice.S8 = arrdata[9];
            modelKtGoldImportprice.S9 = arrdata[10];
            modelKtGoldImportprice.S10 = arrdata[11];
            modelKtGoldImportprice.S11 = arrdata[12];
            modelKtGoldImportprice.S12 = arrdata[13];
            modelKtGoldImportprice.S13 = arrdata[14];
            modelKtGoldImportprice.S14 = arrdata[15];
            modelKtGoldImportprice.S15 = arrdata[16];
            modelKtGoldImportprice.S16 = arrdata[17];
            modelKtGoldImportprice.S17 = arrdata[18];
            modelKtGoldImportprice.S18 = arrdata[19];
            modelKtGoldImportprice.S19 = arrdata[20];
            modelKtGoldImportprice.S20 = arrdata[21];
            modelKtGoldImportprice.Create();  
        }

        private string uploadfile()
        {
            try
            {
                if (upfile.PostedFile != null && upfile.PostedFile.FileName.Length > 0)
                {
                    string FileN = "";
                    FileN = upfile.PostedFile.FileName.ToLower();
                    ViewState["FileN"] = FileN;
                    if (upfile.PostedFile.FileName.ToLower().IndexOf(".xls") < 0)
                    {
                        Page.RegisterClientScriptBlock("sds", "<script lanaguage=javascript>alert('导入文件必须是excel')</script>");
                        return null;
                    }
                    HttpFileCollection objFiles = HttpContext.Current.Request.Files;
                    HttpPostedFile objPostedFile = objFiles[0];
                    strOrgFileName = System.IO.Path.GetFileName(objPostedFile.FileName);
                    strFileExtension = System.IO.Path.GetExtension(strOrgFileName);
                    strCurFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + strFileExtension;
                    filename = Server.MapPath("") + "\\upload\\" + strCurFileName;
                    objPostedFile.SaveAs(filename);
                    return filename;

                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            if (uploadfile() == null)
            {
                
                //Page.RegisterClientScriptBlock("sdss", "<script lanaguage=javascript>alert('未能上传文件，不能预览！')</script>");
                MessageBox.Show(this,"未能上传文件，不能预览！");
                return;
            }
            txtProductName.Text = ViewState["FileN"].ToString();
            Panel1.Visible = true;
            DisplayData();
        }

        private void DisplayData()
        {
            //定义sheet1$表名
            string tableName = null;
            DataTable dt = new DataTable();
            string filename = uploadfile();

            if (filename == null || filename == "")
            {                
                MessageBox.Show(this, "请选择导入文件！");
                return;
            }

            string strConnUpload = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " + filename + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=1'";
            OleDbConnection connUpload = new OleDbConnection(strConnUpload);
            connUpload.Open();
            DataTable dtname = connUpload.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            //获取sheet1$表名
            tableName = dtname.Rows[0][2].ToString().Trim();
            //查询EXCEL
            string strSQL = "SELECT * FROM " + "[" + tableName + "]";
            OleDbDataAdapter daUpload = new OleDbDataAdapter(strSQL, connUpload);

            daUpload.Fill(dt);
            connUpload.Close();
            //返回当前的数据格式 
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void ddlParentKtCommCodelistByPriceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            BindGridView();
        }
        

    }
}
